package com.gary.vueblog.shiro;

import cn.hutool.core.bean.BeanUtil;
import com.gary.vueblog.entity.MUser;
import com.gary.vueblog.service.MUserService;
import com.gary.vueblog.utils.JwtUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author pengrui
 * @date 2020/12/8 - 13:38
 */
@Component
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private MUserService userService;

    /**
     * 判断 doGetAuthenticationInfo() 方法的入参 是否是jwtToken
     * 以便进行强转
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     *  用户认证处理
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) token;
        String userId = jwtUtil.getClaimByToken((String) jwtToken.getPrincipal()).getSubject();
        MUser user = userService.queryById(Long.valueOf(userId));
        if (user == null) {
            throw new UnknownAccountException("用户不存在");
        }

        if (user.getStatus() == -1) {
            throw new LockedAccountException("账户已被锁定");
        }

        AccountProfile profile = new AccountProfile();
        BeanUtil.copyProperties(user, profile);
        System.out.println("------------");
        return new SimpleAuthenticationInfo(profile, jwtToken.getCredentials(), getName());
    }
}
